import java.util.Arrays;

public class TestHeap {
    public int[]elem;
    public int usedSize;
    public TestHeap(){
        this.elem=new int[10];
    }

    public void createHeap(int[]array){
        for (int i = 0; i < array.length; i++) {
            elem[i]=array[i];
            usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    public void shiftDown(int parent,int len){
        int child=2*parent+1;
        while(child<len){
            if(child+1<len&&elem[child+1]>elem[child]){
                child++;
            }
            if(elem[parent]<elem[child]){
                int tmp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=tmp;
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }

    public void offer(int val){
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    public void shiftUp(int child){
        int parent=(child-1)/2;
        while(child>0){
            if(elem[parent]<elem[child]){
                int tmp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=tmp;
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isFull(){
        return usedSize==elem.length;
    }


    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("优先级队列为空！");
        }
        int tmp=elem[0];
        elem[0]=elem[usedSize-1];
        elem[usedSize-1]=tmp;
        usedSize--;
        shiftDown(0,usedSize);
        return tmp;
    }

    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("优先级队列为空！");
        }
        return elem[0];
    }

    public boolean isEmpty(){
        return usedSize==0;
    }

    public void heapSort(){
        int end=usedSize-1;
        while(end>0){
            int tmp=elem[0];
            elem[0]=elem[end];
            elem[end]=tmp;
            shiftDown(0,end);
            end--;
        }
    }

    public static void main(String[] args) {
        TestHeap testHeap=new TestHeap();
        int[]array={3,6,44,22,54,64,43,67};
        testHeap.createHeap(array);
        testHeap.heapSort();
        System.out.println("---");
//        System.out.println("----");
//        testHeap.offer(99);
//        System.out.println("=====");
//        System.out.println(testHeap.poll());
//        System.out.println(testHeap.poll());

    }
}
